package com.kabigon.tiny.web;


import com.kabigon.tiny.config.WxAccountConfig;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.http.URIUtil;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/wechat")
public class WxMpController {

    @Autowired
    private WxMpService wxMpService;
    //@Autowired
    //private RestTemplate restTemplate;
    @Autowired
    private WxAccountConfig wxAccountConfig;

    private Map<String, Object> users = new HashMap<>();

    /**
     * 授权登录
     *
     * @param redirectUrl
     */
    @GetMapping("/authorize")
    public String authorize(@RequestParam("redirectUrl") String redirectUrl) {
        log.info("redirectUri===>{}", redirectUrl);
        String returnUrl = "";

        /**
         * redirectUri：授权后重定向的回调链接地址， 请使用 urlEncode 对链接进行处理
         * scope：应用授权作用域，snsapi_base （不弹出授权页面，直接跳转，只能获取用户openid），
         * snsapi_userinfo （弹出授权页面，可通过openid拿到昵称、性别、所在地。并且， 即使在未关注的情况下，只要用户授权，也能获取其信息 ）
         * state：重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节
         */
        returnUrl = wxMpService.getOAuth2Service().buildAuthorizationUrl(wxAccountConfig.getAccessTokenUrl(), WxConsts.OAuth2Scope.SNSAPI_USERINFO, URIUtil.encodeURIComponent(redirectUrl));
        log.info("微信网页端回调地址：{}", returnUrl);
        return "redirect:" + returnUrl;


    }

    /**
     *
     * @param code
     * @param returnUrl
     * @return
     * @throws WxErrorException
     */
    @GetMapping("/accessToken")
    public String accessToken(@RequestParam("code") String code, @RequestParam(value = "state", required = false) String returnUrl) throws WxErrorException {
        log.info("code===>{}", code);
        log.info("state===>{}", returnUrl);

        // 获取认证token
        WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
        // 从token中获取openid
        String openId = accessToken.getOpenId();
        String unionId = accessToken.getUnionId();

        return "redirect:" + returnUrl + "?token=" + accessToken.getAccessToken() + "&openId=" + openId;


    }

    /**
     *
     * @param params
     */
    @PostMapping("/bindPhone")
    @ResponseBody
    public void bindPhone(@RequestBody HashMap<String, Object> params) {
        log.info("bindPhone ===> {}", params.toString());
    }




}
